package com.easy.dfc.service;

import com.easy.common.bean.Result;
import com.easy.common.constant.EnumConfig;
import com.easy.common.util.Utility;
import com.easy.common.utils.IdGen;
import com.easy.dfc.Utils.Util;
import com.easy.dfc.entity.*;
import com.easy.dfc.mapper.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by VULCANTSeries on 2017/5/17.
 */
@Service
public class EnrollService {


    @Resource
    private DfcActivityMapper activityMapper;
    @Resource
    private DfcActivityEnrollMapper activityEnrollMapper;

    @Resource
    private ProductsetMapper productsetMapper;

    @Resource
    private DfcEnrollMapper enrollMapper;

    @Resource
    private UsersetMapper usersetMapper;

    public Result ActivityEnrollAdd(ParaEnroll para) {
        Result rt = new Result();
        //String uuid = IdGen.uuid();
        String uuid = UUID.randomUUID().toString();
        Integer userId = usersetMapper.getUserId(para.getUserId());
        Integer factoryId = Utility.parseInt(para.getFactoryId());
        DfcActivity activity = activityMapper.getByUuId(para.getActivityId());
        if(userId < 1 || activity == null || factoryId < 1){
            rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
            return rt;

        }
        Date now = new Date();
        DfcEnroll enroll = new DfcEnroll();
        DfcEnrollProduct product = new DfcEnrollProduct();
        enroll.setEnUid(para.getUserId());
        enroll.setEnGuid(uuid);
        enroll.setFactoryId(factoryId);
        enroll.setEnAtID(para.getTypeId());
        enroll.setEnAtName(activity.getSubject());
        enroll.setEnAcID(activity.getId());
        enroll.setEnName(para.getContactName());
        enroll.setEnPhone(para.getContactPhone());
        enroll.setEnEnrollStartDate(para.getStartDate());
        enroll.setEnEnrollEndDate(para.getEndDate());
        enroll.setEnCreateTime(now);
        enroll.setEnStatus(1);
        enroll.setAmnt(activity.getAmnt());

        enrollMapper.insertEnroll(enroll);//老表操作

        ProductsetWithBLOBs productsetWithBLOBs = productsetMapper.selectByUuId(para.getProductId());
        if(productsetWithBLOBs!=null) {
            product.setEpEnUid(enroll.getEnGuid());
            product.setEpFactoryID(Utility.parseInt(para.getFactoryId()));
            product.setEpProductID(productsetWithBLOBs.getProductid());
            product.setEpActivityPrice(para.getPrice());
            product.setEpActivityNum(para.getNum());
            product.setEpRemark(para.getRemark());
            product.setEpIsNormal(0);
            product.setEpAcID(activity.getId());
            product.setEpAtID(activity.getTypeId());
            product.setEpAtName(activity.getSubject());
            enrollMapper.insertEnrollProduct(product);//老表操作
        }
        rt.setStatus(EnumConfig.S_CODE.OK);
        return rt;
    }

    public Result ActivityEnrollAdd1(ParaEnroll1 para) {
        Result rt = new Result();
        //String uuid = IdGen.uuid();
        String uuid = UUID.randomUUID().toString();
        Integer userId = usersetMapper.getUserId(para.getUserId());
        Integer factoryId = Utility.parseInt(para.getFactoryId());
        DfcActivity activity = activityMapper.getByUuId(para.getActivityId());
        if(userId < 1 || activity == null || factoryId < 1){
            rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
            return rt;

        }
        Date now = new Date();

        DfcEnroll enroll = new DfcEnroll();
        DfcEnrollProduct product = new DfcEnrollProduct();
        DfcLive live = new DfcLive();
        enroll.setEnUid(para.getUserId());
        enroll.setEnGuid(uuid);
        enroll.setFactoryId(factoryId);
        enroll.setEnAtID(para.getTypeId());
        enroll.setEnAtName(activity.getSubject());
        enroll.setEnAcID(activity.getId());
        enroll.setEnName(para.getContactName());
        enroll.setEnPhone(para.getContactPhone());
        enroll.setEnEnrollStartDate(para.getStartDate());
        enroll.setEnEnrollEndDate(para.getEndDate());
        enroll.setEnCreateTime(now);
        enroll.setEnStatus(1);
        enroll.setAmnt(activity.getAmnt());

        enrollMapper.insertEnroll(enroll);//老表操作

        for(int i=0;i< para.getProductList().size();i++) {
            ParaEnrollList pr = para.getProductList().get(i);
            ProductsetWithBLOBs productsetWithBLOBs = productsetMapper.selectByUuId(pr.getProductId());
            if(productsetWithBLOBs!=null) {
                product.setEpEnUid(enroll.getEnGuid());
                product.setEpFactoryID(Utility.parseInt(para.getFactoryId()));
                product.setEpProductID(productsetWithBLOBs.getProductid());
                product.setEpActivityPrice(pr.getPrice());
                product.setEpActivityNum(pr.getNum());
                product.setEpRemark(para.getRemark());
                product.setEpIsNormal(0);
                product.setEpAcID(activity.getId());
                product.setEpAtID(activity.getTypeId());
                product.setEpAtName(activity.getSubject());
                enrollMapper.insertEnrollProduct(product);//老表操作
            }
        }

        for(int i=0;i< para.getLiveList().size();i++) {
            ParaActivityLive lv = para.getLiveList().get(i);
            live.setTitle(Utility.null2Empty(lv.getLiveTitle()));
            live.setCoverPlan(Utility.null2Empty(lv.getCoverPlan()));
            live.setVideoUrl(Utility.null2Empty("live"+enroll.getEnGuid().replaceAll("-","")+i));
            live.setActivityId(enroll.getEnAcID());
            live.setEnrollId(enroll.getEnId());
            live.setFactoryId(enroll.getFactoryId());
            live.setLiveStatus("0");
            live.setAuditStatus(String.valueOf(enroll.getEnStatus()));
            live.setStartDate(enroll.getEnEnrollStartDate());
            live.setCreateDate(now);
            live.setDuration(100);
            live.setUserId(userId);
            live.setHavePay(0);
            activityEnrollMapper.insertLive(live);//新表
        }
        rt.setStatus(EnumConfig.S_CODE.OK);
        return rt;
    }

    public Result ActivityEnrollList(ParaEnrollQuery para) {
        Result rt = new Result();
        List<Map<String,Object>> list = enrollMapper.ActivityEnrollList(para);

        for(int i=0;i<list.size();i++){
            Map<String,Object> map = list.get(i);
            Integer status = (Integer)map.get("status");
            if(status==2){
                Map<String,Object> payMap = new HashMap<String,Object>();

                payMap.put("payId",map.get("id"));
                payMap.put("payName","enrollPay");
                payMap.put("payAmnt",map.get("amnt"));
                payMap.put("payFactoryId",para.getFactoryId());
                payMap.put("payProductName",map.get("subject")+"活动报名费");
                payMap.put("payProductDesc","参加"+map.get("startTime")+map.get("subject")+"活动报名费");

                payMap.put("payMode","aliPay,weChatPay");
                map.put("payInfo",payMap);
            }
            list.set(i,map);
        }
        rt.setStatus(EnumConfig.S_CODE.OK);
        rt.setData(list);
        return rt;
    }

    public Result ActivityEnrollCancel(ParaEnrollQuery para) {
        Result rt = new Result();
        enrollMapper.ActivityEnrollCancel(para.getEnrollId());
        rt.setStatus(EnumConfig.S_CODE.OK);
        //rt.setData(list);
        return rt;
    }

    public Result ActivityEnrollDetail(ParaEnrollQuery para) {
        Result rt = new Result();
        Map<String,Object> map = enrollMapper.ActivityEnrollDetail(para.getEnrollId());
        if(map==null){
            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(new HashMap());
            return rt;
        }
        String enrollId = (String)map.get("id");
        Integer typeId = (Integer)map.get("typeId");

        List<Map<String,Object>>productList = enrollMapper.ActivityEnrollProduct(enrollId);
        if(typeId==2){
            map.put("productList",productList);
        }
        rt.setStatus(EnumConfig.S_CODE.OK);
        rt.setData(map);
        return rt;
    }

    public Result ActivityEnrollList1(ParaEnrollQuery para) {
        Result rt = new Result();
        List<Map<String,Object>> list = enrollMapper.ActivityEnrollList1(para);

        for(int i=0;i<list.size();i++){
            Map<String,Object> map = list.get(i);
            Integer status = (Integer)map.get("status");
            if(status==2){
                Map<String,Object> payMap = new HashMap<String,Object>();
                payMap.put("payId",map.get("id"));
                payMap.put("payName","enrollPay");
                payMap.put("payAmnt",map.get("amnt"));
                payMap.put("payFactoryId",para.getFactoryId());
                payMap.put("payProductName",map.get("subject")+"活动报名费");
                payMap.put("payProductDesc","参加"+map.get("startTime")+map.get("subject")+"活动报名费");

                payMap.put("payMode","aliPay,weChatPay");
                map.put("payInfo",payMap);
            }
            String enrollId = (String)map.get("id");
            List<Map<String,Object>>productList = enrollMapper.ActivityEnrollProduct(enrollId);
            map.put("productList",productList);

            List<DfcLive>liveList = enrollMapper.getLiveList(enrollId);
            if(liveList==null)liveList = new ArrayList<DfcLive>();
            map.put("liveList",liveList);
            list.set(i,map);
        }
        rt.setStatus(EnumConfig.S_CODE.OK);
        rt.setData(list);
        return rt;
    }

    public Result ActivityList(ParaActivity para) {
        Result rt = new Result();
        List<Map<String,Object>> list = activityMapper.ActivityList(para);
        Date tdate = new Date(0);
        Integer day = Utility.getDaySpan(para.getStartDate(), para.getEndDate()) + 1;
        List []ls = new ArrayList[day];
        //Map<String,Object> []map = new HashMap[day];

        for(int i =0; i < list.size(); i++){
            Map<String,Object> activity = list.get(i);
            Integer sday = Utility.getDaySpan(para.getStartDate(), (Date)activity.get("startTime"));
            Integer eday = Utility.getDaySpan(para.getEndDate(), (Date)activity.get("endTime"));
            if(sday<1)sday=0;
            if(eday>=day)eday=day;
            for(int j = sday;j< eday;j++){
                if(ls[j] == null) ls[j]= new ArrayList();
                ls[j].add(activity);
            }
        }

        List lst = new ArrayList();
        for(int i = 0; i < day; i++) {
            if(ls[i]==null || ls[i].size()<1)continue;
            Map tmap = new HashMap();
            tmap.put("tdate",Utility.getDateStr(Utility.getDayAfter(para.getStartDate(),i)));
            tmap.put("activity",ls[i]);
            lst.add(tmap);
        }
        rt.setStatus(EnumConfig.S_CODE.OK);
        rt.setData(lst);
        return rt;
    }

    public Result ActivityEnrollPay(ParaPayInfo para,String url) {
        Result rt = new Result();
        Map<String,Object> map = new HashMap<String,Object>();

        Date now = new Date();
        PayProductInfo info = new PayProductInfo();
        info.setTradeNo(Util.getOrderItemNo());
        info.setTotalAmnt(para.getPayAmnt());
        info.setProductName(para.getPayProductName());
        info.setProductDesc(para.getPayProductDesc());
        info.setCreateTime(now);
        info.setExpireTime(new Date(now.getTime()+900000));
        //info.setNotifyUrl(url+"${apiPath}/factory/aliNotify");
        info.setNotifyUrl(url+"aliNotify");

        if(para.getPayMode().equals("aliPay")){
            AliPayInfo aliPay = new AliPayInfo();
            String zBody = aliPay.getAliPayInfo(info);
            map.put("payId",para.getPayId());
            map.put("tradeNo",info.getTradeNo());
            map.put("payName","aliPay");
            map.put("payInfo",zBody);

            enrollMapper.updateTradeNo(para.getPayId(),info.getTradeNo());

        }
        if(para.getPayMode().equals("weChatPay")){
            AliPayInfo aliPay = new AliPayInfo();
            WeChatPayInfo weChatPay = new WeChatPayInfo();
            map.put("payId",para.getPayId());
            map.put("tradeNo",info.getTradeNo());
            map.put("payName","weChatPay");
            map.put("payInfo",weChatPay.getWeChatPayInfo(info));
        }
        rt.setData(map);
        rt.setStatus(EnumConfig.S_CODE.OK);
        return rt;

    }

    public String aliNotify(AliNotify aliNotify) {
        String tradeStatus = aliNotify.getTrade_status();
        if(tradeStatus==null)tradeStatus="";
        if(tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")){//订单支付完成
            String outTradeNo = aliNotify.getOut_trade_no();
            DfcEnroll Enroll = enrollMapper.findByTradeNo(outTradeNo);
            if(Enroll != null){
                enrollMapper.updateSucessStatus(Enroll.getEnGuid());
            }

        }
        else if(tradeStatus.equals("TRADE_CLOSED")){//订单关闭
            //String outTradeNo = aliNotify.getOut_trade_no();
            //DfcFactoryUpgrade upgrade = factoryUpgradeMapper.findByTradeNo(outTradeNo);
            //if(upgrade != null){
            //    factorySetMapper.updateFactoryType(upgrade.getFactoryId(),upgrade.getUpgradeId());
            //    factoryUpgradeMapper.updateFailStatus(upgrade.getId());
            //}
        }
        else {//其他错误
            //String outTradeNo = aliNotify.getOut_trade_no();
            //DfcFactoryUpgrade upgrade = factoryUpgradeMapper.findByTradeNo(outTradeNo);
            //if(upgrade != null){
            //    factorySetMapper.updateFactoryType(upgrade.getFactoryId(),upgrade.getUpgradeId());
            //    factoryUpgradeMapper.updateFailStatus(upgrade.getId());
            //}
        }
        return "success";
    }


    public void saveLog(String alipay) {
        enrollMapper.saveLog(alipay);
    }
}
